// (c) Copyright Fernando Cerqueira.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;

// ReSharper disable CheckNamespace
namespace WindowsPhoneCommands
// ReSharper restore CheckNamespace
{
    [Serializable]
    public class WpIsolateSaveData
    {
        #region Singleton

        private static WpIsolateSaveData _current;

        public static WpIsolateSaveData Current
        {
            get { return _current ?? (_current = Load()); }
        }

        #endregion

        public Collection<WpDeployApplication> WpApplication { get; set ; }

        private WpIsolateSaveData()
        {
            WpApplication = new Collection<WpDeployApplication>();
        }

        internal void AddData(WpDeployApplication data)
        {
            var item = WpApplication.FirstOrDefault(wp => wp.Guid == data.Guid);
            if (item == null)
            {
                WpApplication.Add(data);
            }
            else
            {
                WpApplication.Remove(item);
                WpApplication.Add(data);
            }
            Save();
        }

        private static WpIsolateSaveData Load()
        {
            var filename = Path.Combine(Common.FolderData(), Constants.IsolateFileName);
            var result = new WpIsolateSaveData();
            if (File.Exists((filename)))
            {
                try
                {
                    using (var stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var formatter = new System.Xml.Serialization.XmlSerializer(new WpIsolateSaveData().GetType());
                        result = formatter.Deserialize(stream) as WpIsolateSaveData;
                    }
                }
                catch
                { 
                    //OLD FORMAT XML, IGNORE ERROR
                }
            }
            return result;
        }

        internal static void Save()
        {
            var filename = Path.Combine(Common.FolderData(), Constants.IsolateFileName);

            using (var stream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                var formatter = new System.Xml.Serialization.XmlSerializer(new WpIsolateSaveData().GetType());
                formatter.Serialize(stream, _current);
            }
        }

    }
}